<template>
  <div class="center-container">
    <el-card class="center-card">
      <template #header>
        <div class="card-header">
          <h3>宿舍报修</h3>
        </div>
      </template>

      <!-- 报修表单 -->
      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px" class="user-form">
        <el-form-item label="报修类型" prop="baoxiuleixing">
          <el-select v-model="form.baoxiuleixing" placeholder="请选择报修类型">
                          <el-option
                v-for="(item, index) in typeList"
                :key="item?.id || index"
                :label="item?.baoxiuleixing || ''"
                :value="item?.baoxiuleixing || ''"
              />
          </el-select>
        </el-form-item>

        <el-form-item label="详情描述" prop="xiangqingmiaoshu">
          <el-input
            type="textarea"
            v-model="form.xiangqingmiaoshu"
            placeholder="请详细描述维修问题"
          />
        </el-form-item>

        <el-form-item label="报修图片">
          <el-upload
            class="upload-demo"
            :auto-upload="false"
            :show-file-list="false"
            :on-change="handleImageChange"
          >
            <el-button type="primary">上传图片</el-button>
          </el-upload>
          <img v-if="form.baoxiutupian"
          :src="`/springbootyyh3w/file/download?fileName=${form.baoxiutupian}`"
          class="preview-img"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm">提交报修</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 历史记录 -->
      <el-divider content-position="left">报修记录</el-divider>
      <el-table :data="historyList" style="width: 100%" v-loading="loading">
        <el-table-column prop="baoxiuleixing" label="类型" />
        <el-table-column prop="xiangqingmiaoshu" label="描述" />
        <el-table-column prop="sfsh" label="状态" />
        <el-table-column prop="addtime" label="时间" />
      </el-table>
      <el-pagination
        style="margin-top: 20px; text-align: center"
        background
        layout="prev, pager, next"
        :total="total"
        :page-size="pageSize"
        :current-page="currentPage"
        @current-change="handlePageChange"
      />
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'
import { repairAPI, fileAPI } from '@/utils/api'

const formRef = ref(null)

const form = reactive({
  baoxiuleixing: '',
  xiangqingmiaoshu: '',
  baoxiutupian: '',
  loudonghao: '',
  sushehao: ''
})

const rules = {
  baoxiuleixing: [{ required: true, message: '请选择报修类型', trigger: 'change' }],
  xiangqingmiaoshu: [{ required: true, message: '请填写描述', trigger: 'blur' }]
}

const typeList = ref([])
const historyList = ref([])
const loading = ref(false)

const currentPage = ref(1)
const pageSize = 10
const total = ref(0)

const xueshengzhanghao = localStorage.getItem('username') || ''
const xueshengxingming = localStorage.getItem('name') || ''

const userId = ref(null)

const getRepairTypes = async () => {
  try {
    const { data } = await axios.get('/springbootyyh3w/baoxiuleixing/list')
    if (data.code === 0) {
      typeList.value = data.data.list.filter(item => item && item.id)
    }
  } catch (error) {
    console.error('获取报修类型失败:', error)
    ElMessage.error('获取报修类型失败')
  }
}

const getHistory = async () => {
  loading.value = true
  try {
    const res = await repairAPI.getList({
      xueshengzhanghao,
      page: currentPage.value,
      limit: pageSize
    })
    if (res.code === 0) {
      historyList.value = res.data.list
      total.value = res.data.total
    }
  } finally {
    loading.value = false
  }
}

const handlePageChange = (page) => {
  currentPage.value = page
  getHistory()
}

const handleImageChange = async (file) => {
  try {
    console.log('上传文件:', file.raw)
    const res = await fileAPI.upload(file.raw)
    console.log('上传响应:', res)

    if (res && res.code === 0) {
      form.baoxiutupian = res.file
      ElMessage.success('上传成功')
    } else {
      ElMessage.error(res?.msg || '上传失败')
    }
  } catch (err) {
    console.error('上传异常:', err)
    ElMessage.error('上传失败')
  }
}

const submitForm = () => {
  formRef.value.validate(async (valid) => {
    if (!valid) return

    try {
      const payload = {
        ...form,
        xueshengzhanghao,
        xueshengxingming,
        sfsh: '待审核',
        loudonghao: form.loudonghao,
        sushehao: form.sushehao,
      }
      const res = await repairAPI.save(payload)
      if (res.code === 0) {
        ElMessage.success('报修提交成功')
        resetForm()
        getHistory()
      } else {
        ElMessage.error(res.msg || '提交失败')
      }
    } catch (error) {
      console.error(error)
      ElMessage.error('提交失败')
    }
  })
}

const resetForm = () => {
  form.baoxiuleixing = ''
  form.xiangqingmiaoshu = ''
  form.baoxiutupian = ''
}

onMounted(async () => {
  await getRepairTypes()
  await getHistory()

  const token = localStorage.getItem('Token') || ''
  const headers = { headers: { token } }

  const sessionRes = await axios.get('/springbootyyh3w/xuesheng/session', headers)
  if (sessionRes.data.code === 0) {
    const user = sessionRes.data.data
    userId.value = user.id
    form.loudonghao = user.loudong
    form.sushehao = user.sushe
  }
})
</script>

<style scoped>
.center-container {
  padding: 20px;
}
.center-card {
  max-width: 800px;
  margin: 0 auto;
}
.preview-img {
  width: 120px;
  margin-top: 10px;
  border-radius: 4px;
}
</style>